<%@ page pageEncoding="utf-8"%>
<%@ page import="org.jawa.core.JawaServer"%>
<%@ page
	import="java.lang.Throwable,java.sql.Connection,java.sql.SQLException,java.sql.Statement,java.util.ArrayList,java.util.HashMap,java.util.List,java.util.Map,org.jawa.core.util.*,org.jawa.admin.util.*,org.jawa.core.database.*,java.io.File"%>
<%
	// 系统已安装
	if (!JawaServer.getInstance().isSetupMode()) {
        response.sendRedirect("setup-completed.jsp");
        return;
    }
%>	
<%!
boolean testConnection(Map<String, String> errors, String driver, String serverURL, String username, String password) {
		boolean success = true;
		Connection con = null;
		try {
			Class.forName(driver);
			con = java.sql.DriverManager.getConnection(serverURL, username, password);
		} catch (SQLException ex) {
			success = false;
			errors.put("general", "无法创建数据库连接. 详细情况请查看错误日志 " + "\"" + File.separator + "logs" + File.separator
					+ "error.log\" 文件 .");

		} catch (ClassNotFoundException ex) {
			success = false;
			errors.put("general", "无法加载数据库驱动. 请确认驱动程序存在于 classpath 中或 服务器应用下的 lib 文件夹中 ,如果你将驱动增加后请重启应用服务器.");
		} finally {
			try {
				con.close();
			} catch (Exception ignored) {
			}
		}
		return success;
	}
%>
<%
	// Get parameters
	String driver = ParamUtils.getParameter(request, "driver");
	String serverURL = ParamUtils.getParameter(request, "serverURL");
	String username = ParamUtils.getParameter(request, "username", true);
	String password = ParamUtils.getParameter(request, "password", true);
	int minConnections = ParamUtils.getIntParameter(request, "minConnections", -1);
	int maxConnections = ParamUtils.getIntParameter(request, "maxConnections", -1);
	double connectionTimeout = ParamUtils.getDoubleParameter(request, "connectionTimeout", 0.0);
	String hdialect = ParamUtils.getParameter(request, "hdialect");
	boolean doContinue = request.getParameter("continue") != null;

	// handle a continue request
	Map<String, String> errors = new HashMap<String, String>();
	if (doContinue) {
		// Error check
		if (driver == null || "sun.jdbc.odbc.JdbcOdbcDriver".equals(driver)) {
			errors.put("driver", "请输入正确的JDBC 驱动程序.");
		} else {
			try {
				ClassUtils.forName(driver);
			} catch (Throwable t) {
				errors.put("driver", "不能加载指定的 JDBC 驱动.");
			}
		}
		if (serverURL == null) {
			errors.put("serverURL", "请输入正确的数据库 URL.");
		}
		if (minConnections < 3) {
			errors.put("minConnections", "最小数据库连接数不能低于3.");
		}
		if (maxConnections < minConnections) {
			errors.put("maxConnections", "最大数据库连接数据不能低于最小数据加连接数.");
		}
		if (connectionTimeout <= 0.0) {
			errors.put("connectionTimeout", "请输入正确的连接超时.");
		}
	
		if (errors.size() == 0) {
			JawaGlobals.setXMLProperty("connectionProvider.className","org.jawa.database.DefaultConnectionProvider");
            DefaultConnectionProvider conProvider = new DefaultConnectionProvider();
			try {
				conProvider.setDriver(driver);
                conProvider.setConnectionTimeout(connectionTimeout);
                conProvider.setMinConnections(minConnections);
                conProvider.setMaxConnections(maxConnections);
                conProvider.setServerURL(serverURL);
                conProvider.setUsername(username);
                conProvider.setPassword(password);
                conProvider.setTestSQL(DbConnectionManager.getTestSQL(driver));
                
				JawaGlobals.setXMLProperty("database.defaultProvider.driver", driver);
				JawaGlobals.setXMLProperty("database.defaultProvider.serverURL", serverURL);
				JawaGlobals.setXMLProperty("database.defaultProvider.username", username);
				JawaGlobals.setXMLProperty("database.defaultProvider.password", password);

				JawaGlobals.setXMLProperty("database.defaultProvider.minConnections", Integer.toString(minConnections));
				JawaGlobals.setXMLProperty("database.defaultProvider.maxConnections", Integer.toString(maxConnections));
				JawaGlobals.setXMLProperty("database.defaultProvider.connectionTimeout", Double.toString(connectionTimeout));
				
			} catch (Exception e) {
				errors.put("general", "设置数据库连接属性发生错误! - 请在日志文件中查看详细情况.");
			}
			
			DbConnectionManager.setConnectionProvider(conProvider);
			if (testConnection(errors, driver, serverURL, username, password)) {
					// 成功
					response.sendRedirect("setup-clustering-settings.jsp");
					return;
			}  
		}
	}

	if (!doContinue) {
		try {
			driver = JawaGlobals.getXMLProperty("database.defaultProvider.driver");
			serverURL = JawaGlobals.getXMLProperty("database.defaultProvider.serverURL");
			username = JawaGlobals.getXMLProperty("database.defaultProvider.username");
			password = JawaGlobals.getXMLProperty("database.defaultProvider.password");
		} catch (Exception e) {
		}
		try {
			minConnections = Integer.parseInt(JawaGlobals
					.getXMLProperty("database.defaultProvider.minConnections"));
		} catch (Exception e) {
			minConnections = 5;
		}
		try {
			maxConnections = Integer.parseInt(JawaGlobals
					.getXMLProperty("database.defaultProvider.maxConnections"));
		} catch (Exception e) {
			maxConnections = 25;
		}
		try {
			connectionTimeout = Double.parseDouble(JawaGlobals
					.getXMLProperty("database.defaultProvider.connectionTimeout"));
		} catch (Exception e) {
			connectionTimeout = 1.0;
		}
	}
%>
<%
	// DB preset data
	List<String[]> presets = new ArrayList<String[]>();
	presets.add(new String[] { "MySQL", "com.mysql.jdbc.Driver",
			"jdbc:mysql://[host-name]:3306/[database-name]", "org.hibernate.dialect.MySQLInnoDBDialect" });
	presets.add(new String[] { "Oracle", "oracle.jdbc.driver.OracleDriver",
			"jdbc:oracle:thin:@[host-name]:1521:[SID]", "org.hibernate.dialect.Oracle9Dialect" });
	presets
			.add(new String[] { "Microsoft SQLServer", "net.sourceforge.jtds.jdbc.Driver",
					"jdbc:jtds:sqlserver://[host-name]:3683/[database-name]",
					"org.hibernate.dialect.SQLServerDialect" });
	presets.add(new String[] { "PostgreSQL", "org.postgresql.Driver",
			"jdbc:postgresql://[host-name]:5432/[database-name]", "org.hibernate.dialect.PostgreSQLDialect" });
	presets.add(new String[] { "IBM DB2", "com.ibm.db2.jcc.DB2Driver",
			"jdbc:db2://[host]:50000/[database-name]", "cirrus.hibernate.sql.DB2Dialect" });
%>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>标准数据库连接</title>
		<meta name="currentStep" content="2" />
	</head>
	<body>
		<div class="row-fluid">
			<div class="page-header">
				<h3>
					标准数据库连接
				</h3>
			</div>
			<%
				if (errors.size() > 0) {
			%>
			<div class="alert alert-error fade in">
				<%=errors.get("general")!=null?errors.get("general"):"发生错误!"%>
			</div>
			<%
				}
			%>
			<div class="well">
				<form action="setup-datasource-standard-settings.jsp" method="post"
					name="dbform" onsubmit="return checkSubmit();"
					class=" form-horizontal">
					<div class="control-group ">
						<label class="control-label">
							数据库类型:
						</label>
						<div class="controls">
							<select name="presets"
								onchange="populate(this.options[this.selectedIndex].value)"
								class="">
								<option value="">
									使用数据库
								</option>
								<%
									for (int i = 0; i < presets.size(); i++) {
										String[] data = presets.get(i);
								%>
								<option value="<%=i%>">
									&#149;
									<%=data[0]%>
								</option>
								<%
									}
								%>
							</select>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("driver") ? "error" : ""%>">
						<label class="control-label">
							JDBC 驱动程序：
						</label>
						<div class="controls">
							<input type="text" name="driver" size="50" maxlength="150" value="<%=((driver != null) ? driver : "")%>" class="input-xlarge "/>
							<%
								if (errors.get("driver") != null) {
							%>
							<span class="help-inline"> <%=errors.get("driver")%></span>
							<%
								}
							%>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("serverURL") ? "error" : ""%>">
						<label class="control-label">
							数据库 URL：
						</label>
						<div class="controls">
							<input type="text" name="serverURL" size="50" maxlength="150" value="<%=((serverURL != null) ? serverURL : "")%>" class="input-xlarge span5"/>
							<%
								if (errors.get("serverURL") != null) {
							%>
							<span class="help-inline"> <%=errors.get("serverURL")%></span>
							<%
								}
							%>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("username") ? "error" : ""%>">
						<label class="control-label">
							数据库用户：
						</label>
						<div class="controls">
							<input type="text" name="username" size="50" maxlength="15" value="<%=((username != null) ? username : "")%>" class="input-xlarge "/>
							<%
								if (errors.get("username") != null) {
							%>
							<span class="help-inline"> <%=errors.get("username")%></span>
							<%
								}
							%>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("password") ? "error" : ""%>">
						<label class="control-label">
							数据库密码：
						</label>
						<div class="controls">
							<input type="text" name="password" size="50" maxlength="15" value="<%=((password != null) ? password : "")%>" class="input-xlarge "/>
							<%
								if (errors.get("password") != null) {
							%>
							<span class="help-inline"> <%=errors.get("password")%></span>
							<%
								}
							%>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("minConnections") ? "error" : ""%>">
						<label class="control-label">
							最小连接数：
						</label>
						<div class="controls">
							<input type="text" name="minConnections" size="3" maxlength="5" value="<%=((minConnections != -1) ? "" + minConnections : "")%>" class="input-xlarge "/>
							<%
								if (errors.get("minConnections") != null) {
							%>
							<span class="help-inline"> <%=errors.get("minConnections")%></span>
							<%
								}
							%>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("maxConnections") ? "error" : ""%>">
						<label class="control-label">
							最大连接数：
						</label>
						<div class="controls">
							<input type="text" name="maxConnections" size="3" maxlength="5" value="<%=((maxConnections != -1) ? "" + maxConnections : "")%>" class="input-xlarge "/>
							<%
								if (errors.get("maxConnections") != null) {
							%>
							<span class="help-inline"> <%=errors.get("maxConnections")%></span>
							<%
								}
							%>
						</div>
					</div>
					<div class="control-group <%=errors.containsKey("maxConnections") ? "error" : ""%>">
						<label class="control-label">
							连接超时：
						</label>
						<div class="controls">
							<input type="text" name="connectionTimeout" size="3" maxlength="5" value="<%=connectionTimeout%>" class="input-xlarge "/>
							(天)
							<%
								if (errors.get("connectionTimeout") != null) {
							%>
							<span class="help-inline"> <%=errors.get("connectionTimeout")%></span>
							<%
								}
							%>
						</div>
					</div>
					
					<div class="form-actions">
						<input type="button" value="上一步" id="jawa-setup-prev" class="btn btn-info "  onclick="window.location.href='setup-datasource-settings.jsp'" />
						<input type="submit" name="continue" value="下一步" id="jawa-setup-next" class="btn btn-primary " />
					</div>
					<blockquote>
					  <p>连接数据库可能需要较长间,请耐心等待.</p>
					</blockquote>
				</form>
			</div>
		</div>

		<script>
			var data = new Array();
			<%for (int i = 0; i < presets.size(); i++) {
				String[] data = presets.get(i);%>
			    data[<%=i%>] = new Array('<%=data[0]%>','<%=data[1]%>','<%=data[2]%>','<%=data[3]%>');
			<%}%>
			function populate(i) {
			    document.dbform.driver.value=data[i][1];
			    document.dbform.serverURL.value=data[i][2];
			}
			var submitted = false;
			function checkSubmit() {
			    if (!submitted) {
			        submitted = true;
			        return true;
			    }
			    return false;
			}
		</script>
	</body>
</html>